/*
 * JPanelPrincipal.java
 *
 * Created on 28 de Outubro de 2008, 13:25
 */
package br.unifor.redes1.odirabel.gui.client;


import br.unifor.redes1.odirabel.ConfigProperties;
import br.unifor.redes1.odirabel.Util;
import br.unifor.redes1.odirabel.gui.server.Cliente;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

/**
 *
 * @author  U013876
 */
public class JPanelPrincipal extends javax.swing.JPanel implements Runnable {

    private JFrameClient frame;
    private Chat chat;
    private Socket socket;
    private BufferedReader input;
    private PrintWriter output;
    private String resposta;
    private String login;
    private Vector<Cliente> listaUsersPersist;
    private Cliente clienteAux;

    JPanelPrincipal(String login, JFrameClient frame, Socket socketParam) {
        try {
            this.socket = socketParam;
            input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            output = new PrintWriter(socket.getOutputStream(), true);
            this.login = login;
            initComponents();
            this.frame = frame;
            chat = new Chat(frame, Boolean.FALSE);
            jLabel1.setText(login + " Logado");
            treeListener();
            servidorNoCliente();


        } catch (IOException ex) {
            JOptionPane.showConfirmDialog(null, ex.getMessage());
        }
    }

    private void servidorNoCliente() {
        try {
            new ServidorNoCliente(this).start();
        } catch (IOException ex) {
            JOptionPane.showConfirmDialog(null, ex.getMessage());
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        jPanel2 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();

        setLayout(new java.awt.BorderLayout());

        jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel1.setText("PedroBelmino - Logado");
        jPanel1.add(jLabel1);

        add(jPanel1, java.awt.BorderLayout.PAGE_START);

        jScrollPane1.setViewportView(jTree1);

        add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jButton1.setText("Visualizar Conversas");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton1);

        add(jPanel2, java.awt.BorderLayout.PAGE_END);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        getChat().setVisible(Boolean.TRUE);
    }//GEN-LAST:event_jButton1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTree jTree1;
    // End of variables declaration//GEN-END:variables

    @Override
    public void run() {
        while (Boolean.TRUE) {
            try {
                output.println("REQUEST_USER_ALL");
                resposta = input.readLine();
                if (resposta.contains("RESPONSE_USER_ALL")) {
                    String users = resposta.substring("RESPONSE_USER_ALL".length() + 1);
                    tryUsers(users);
                }
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ex) {
                   JOptionPane.showConfirmDialog(null, ex.getMessage());
                }
            } catch (IOException ex) {
                JOptionPane.showConfirmDialog(null, ex.getMessage());
            }
        }
    }

    private void treeListener() {
        jTree1.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                clickTree(e);
            }
        });
    }

    public void clickTree(MouseEvent e) {
        if (e.getClickCount() == 2) {
            try {
                TreePath selPath = jTree1.getPathForLocation(e.getX(), e.getY());
                String c = selPath.getLastPathComponent().toString();
                Cliente cli = Util.stringToUser(c);
                System.out.println("Cliente " + cli.getIp());
                UsuarioChat userChat = new UsuarioChat(this.login, cli, new Socket(cli.getIp(),Integer.parseInt( ConfigProperties.getInstance().getProperty("portacliente"))));
                getChat().getJTabbedPane1().add(userChat, cli.getLogin());
                new Thread(userChat).start();
                getChat().setVisible(Boolean.TRUE);
            } catch (UnknownHostException ex) {
                JOptionPane.showConfirmDialog(null, ex.getMessage());
            } catch (IOException ex) {
               JOptionPane.showConfirmDialog(null, ex.getMessage());
            }
        }
    }

    private void tryUsers(String users) {
        String[] usersList = users.split(" ");
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("amigos");
        DefaultMutableTreeNode aux;
        if (getListaUsersPersist() == null) {
            setListaUsersPersist((Vector<Cliente>) new Vector());
        }
        getListaUsersPersist().clear();
        for (int i = 0; i < usersList.length; i = i + 2) {
            if (!usersList[i].equals(login)) {
                clienteAux = new Cliente(usersList[i], usersList[i + 1]);
                aux = new DefaultMutableTreeNode(clienteAux.toString());
                getListaUsersPersist().add(clienteAux);
                root.add(aux);
            }

        }
        jTree1.setModel(new DefaultTreeModel(root));
    }

    /**
     * @return the chat
     */
    public Chat getChat() {
        return chat;
    }

    /**
     * @return the login
     */
    public String getLogin() {
        return login;
    }

    /**
     * @return the listaUsersPersist
     */
    public Vector<Cliente> getListaUsersPersist() {
        return listaUsersPersist;
    }

    /**
     * @param listaUsersPersist the listaUsersPersist to set
     */
    public void setListaUsersPersist(Vector<Cliente> listaUsersPersist) {
        this.listaUsersPersist = listaUsersPersist;
    }
}
